<template>
  <div>
    <div
      style="
        border-bottom: 3px solid #409eff;
        margin-bottom: 15px;
        height: 45px;
      "
    >
      <span style="font-size: 28px">注册新用户</span>
    </div>

    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="form.confirmPassword"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="form.code" placeholder="请输入验证码"></el-input>
        <el-button type="text" class="get-code-btn" @click="handleGetCode" :disabled="isDisabled">
          {{this.isDisabled
          ? `${this.secondsLeft}秒后重发`
          : "发送验证码"}}
        </el-button>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="form.sex">
          <el-radio label="1">男</el-radio>
          <el-radio label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label-width="0px">
        <el-button type="primary" @click="submitForm" v-if="!this.loading">注册新用户</el-button>
        <el-button type="primary" :loading="this.loading" v-else>加载中</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="text" @click="goToLogin" style="float: right">已有账号？去登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
        confirmPassword: "",
        phone: "",
        code: "",
        sex: "1",
      },
      isDisabled: false, // 初始不禁用按钮
      lastClickTime: 0, // 存储最近一次点击时间戳
      secondsLeft: 0, // 倒计时秒数
      loading: false, //改变加载样式
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "密码长度在6到20个字符之间",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: this.validateConfirmPassword, trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
    };
  },
  methods: {
    async handleGetCode() {
      // 处理获取验证码
      if (!this.form.phone) {
        this.$message.error("请填写手机号码");
        return;
      }
      this.countdownClick();
      // 调用后端接口发送验证码，这里使用假数据代替
      await this.$axios
        .post("/api/user/sendMsg?phone=" + this.form.phone)
        .then((res) => {
          if (res.data.code == 1) {
            this.$notify({
              title: "获取验证码成功",
              message: res.data.msg,
              type: "success",
            });
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((error) => {
          // 处理请求失败的错误
          this.$message.error(error.response.data.msg);
        });
    },

    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          // 在这里提交表单
          await this.$axios
            .post("/api/user/signup", this.form)
            .then((res) => {
              if (res.data.code === 1) {
                localStorage.setItem("userToken", res.data.data);
                this.$message.success(res.data.msg);
                this.loading = false;
                this.$router.push("/");
              } else if (res.data.code === 0) {
                this.$message.error(res.data.msg);
              }
            })
            .catch((error) => {
              this.loading = false;
              // 处理请求失败的错误
              this.$message.error(error.response.data.msg);
            });
          this.loading = false;
        } else {
          this.$message.error("请正确填写信息");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    goToLogin() {
      this.$router.push("/loginRegistration");
    },
    //确认密码规则
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.form.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    },
    // 倒计时60秒方法
    countdownClick() {
      // 点击触发60秒倒计时
      if (this.isDisabled) {
        return;
      }
      this.isDisabled = true; // 禁用按钮
      this.secondsLeft = 60; // 设置初始倒计时秒数
      this.lastClickTime = Date.now(); // 存储当前点击时间戳
      localStorage.setItem("lastClickTime", this.lastClickTime);
      this.countdown(); // 开始倒计时
    },
    // 开始倒计时
    countdown() {
      if (this.secondsLeft === 0) {
        this.isDisabled = false; // 解除禁用
        return;
      }
      this.secondsLeft--;
      setTimeout(() => {
        this.countdown();
      }, 1000); // 每一秒更新倒计时秒数
    },
    //获取时间戳
    getTimestamp() {
      const lastClickTime = localStorage.getItem("lastClickTime"); // 获取最近一次点击时间戳
      if (lastClickTime !== null && Date.now() - +lastClickTime < 60000) {
        // 如果距离上次点击时间小于60秒
        this.isDisabled = true; // 禁用按钮
        this.secondsLeft = Math.ceil(60 - (Date.now() - +lastClickTime) / 1000);
        this.countdown(); // 开始倒计时
      } else {
        this.isDisabled = false; // 不禁用按钮
        localStorage.removeItem("lastClickTime");
      }
    },
  },
  mounted() {
    this.getTimestamp();
  },
};
</script>

<style scoped>
.get-code-btn {
  float: right;
  margin-top: 5px;
}
</style>
